<template>
  <div class="videos-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-icon">
          <el-icon><VideoPlay /></el-icon>
        </div>
        <div class="header-text">
          <h2>我的视频</h2>
          <p>共 {{ videoUrls.length }} 个视频文件</p>
        </div>
      </div>

      <div class="header-actions">
        <el-button @click="refreshVideos">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
        <el-button type="primary" @click="$router.push('/fileupload')">
          <el-icon><Upload /></el-icon>
          上传视频
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filter-section">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索视频文件..."
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="12">
          <div class="view-controls">
            <el-radio-group v-model="viewMode">
              <el-radio-button label="grid">
                <el-icon><Grid /></el-icon>
                网格视图
              </el-radio-button>
              <el-radio-button label="list">
                <el-icon><List /></el-icon>
                列表视图
              </el-radio-button>
            </el-radio-group>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 视频内容 -->
    <div class="videos-content">
      <div v-if="loading" class="loading-state">
        <el-icon class="is-loading"><Loading /></el-icon>
        <p>正在加载视频...</p>
      </div>

      <div v-else-if="filteredVideos.length === 0" class="empty-state">
        <el-empty description="暂无视频文件">
          <el-button type="primary" @click="$router.push('/fileupload')">
            上传第一个视频
          </el-button>
        </el-empty>
      </div>

      <!-- 网格视图 -->
      <div v-else-if="viewMode === 'grid'" class="grid-view">
        <div
          v-for="(video, index) in filteredVideos"
          :key="video.id"
          class="video-card"
        >
          <div class="video-header">
            <h3 class="video-title" :title="video.filename">{{ video.filename }}</h3>
            <div class="video-actions">
              <el-dropdown trigger="click">
                <el-button type="text" class="action-btn">
                  <el-icon><MoreFilled /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="downloadVideo(video)">
                      <el-icon><Download /></el-icon>
                      下载
                    </el-dropdown-item>
                    <el-dropdown-item @click="shareVideo(video)">
                      <el-icon><Share /></el-icon>
                      分享
                    </el-dropdown-item>
                    <el-dropdown-item @click="deleteVideo(index)" divided>
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>

          <div class="video-player-wrapper">
            <video
              :src="video.videoUrl || video.relativeFilePath"
              :poster="video.poster"
              controls
              controlslist="nodownload"
              preload="metadata"
              class="custom-video-player"
              @play="onVideoPlay(index)"
              @pause="onVideoPause(index)"
              @ended="onVideoEnded(index)"
              @loadedmetadata="onVideoLoadedMetadata(index)"
              @error="onVideoError(index, $event)"
            />

            <!-- 调试信息 -->
            <div class="video-debug-info" v-if="showDebugInfo">
              <p><small>URL: {{ video.videoUrl }}</small></p>
              <p><small>状态: {{ getVideoStatus(index) }}</small></p>
            </div>
          </div>

          <div class="video-info">
            <div class="video-meta">
              <span class="video-date">{{ formatDate(video.created_at) }}</span>
              <span class="video-size">{{ formatFileSize(video.size) }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 列表视图 -->
      <div v-else class="list-view">
        <el-table :data="filteredVideos" style="width: 100%" v-loading="loading">
          <el-table-column label="视频" min-width="300">
            <template #default="{ row }">
              <div class="video-cell">
                <div class="video-thumbnail">
                  <el-icon><VideoPlay /></el-icon>
                </div>
                <div class="video-details">
                  <div class="video-name">{{ row.filename }}</div>
                  <div class="video-meta-list">
                    <span>{{ formatDate(row.created_at) }}</span>
                    <span>{{ formatFileSize(row.size) }}</span>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row, $index }">
              <el-button size="small" @click="playVideo(row)">
                <el-icon><VideoPlay /></el-icon>
                播放
              </el-button>
              <el-button size="small" @click="downloadVideo(row)">
                <el-icon><Download /></el-icon>
                下载
              </el-button>
              <el-button type="danger" size="small" @click="deleteVideo($index)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 视频播放对话框 -->
    <el-dialog
      v-model="playDialogVisible"
      :title="currentVideo?.filename"
      width="80%"
      :before-close="closePlayDialog"
    >
      <div class="dialog-video-player">
        <video
          v-if="currentVideo"
          :src="currentVideo.videoUrl || currentVideo.relativeFilePath"
          controls
          autoplay
          controlslist="nodownload"
          class="dialog-video"
          @ended="playNextVideo"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import {
  VideoPlay,
  Refresh,
  Upload,
  Search,
  Grid,
  List,
  MoreFilled,
  Download,
  Share,
  Delete,
  Loading
} from "@element-plus/icons-vue";
import { getVideoApi, deleteApi, downloadApi } from "@/utils/api";
// import VideoPlayer from "@/components/VideoPlayer.vue";

const router = useRouter();

// 响应式数据
const videoUrls = ref([]);
const loading = ref(false);
const searchKeyword = ref("");
const viewMode = ref("grid");
const playDialogVisible = ref(false);
const currentVideo = ref(null);
const currentPlayingIndex = ref(-1);
const showDebugInfo = ref(false);
const videoStatuses = ref({});

// 计算属性
const filteredVideos = computed(() => {
  if (!searchKeyword.value) return videoUrls.value;
  return videoUrls.value.filter(video =>
    video.filename.toLowerCase().includes(searchKeyword.value.toLowerCase())
  );
});

// 方法
const getVideos = async () => {
  loading.value = true;
  try {
    const id = localStorage.getItem("id");
    const response = await getVideoApi({ id });
    console.log("视频API响应:", response);

    if (response && response.code === 200 && Array.isArray(response.data)) {
      videoUrls.value = response.data.map((item) => ({
        ...item,
        // 从relativeFilePath中提取实际的文件名
        actualFilename: extractFilenameFromPath(item.relativeFilePath),
        // 使用支持Range请求的视频流媒体URL
        videoUrl: generateStreamingUrl(extractFilenameFromPath(item.relativeFilePath)),
        // 保留原始URL作为备用
        originalUrl: item.relativeFilePath,
        created_at: item.created_at ? item.created_at.split("T")[0] : new Date().toISOString().split("T")[0],
        // 格式化文件大小
        formattedSize: formatFileSize(item.size || 0)
      }));
      console.log("处理后的视频数据:", videoUrls.value);
    } else {
      console.warn("API响应格式不正确:", response);
      videoUrls.value = [];
      ElMessage.warning("未找到视频文件");
    }
  } catch (error) {
    console.error("获取视频失败:", error);
    ElMessage.error("获取视频失败");
    videoUrls.value = [];
  } finally {
    loading.value = false;
  }
};

const refreshVideos = () => {
  getVideos();
  ElMessage.success("已刷新视频列表");
};

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
};

// 从完整路径中提取文件名
const extractFilenameFromPath = (fullPath) => {
  if (!fullPath) return '';
  // 从URL中提取文件名部分
  // 例如: "http://192.168.31.222:3000/fileUploadDownload/image/admin/èèå¸¥å¥_Recsonxxx_ç¡å¥_1_1753474446877_3684f1c8.mp4"
  const parts = fullPath.split('/');
  return parts[parts.length - 1]; // 获取最后一部分作为文件名
};

// 生成支持Range请求的流媒体URL
const generateStreamingUrl = (filename) => {
  const username = localStorage.getItem("username");
  const baseUrl = "http://192.168.31.222:3000";
  // 使用现有的图片路由，它现在也支持视频的Range请求
  return `${baseUrl}/fileUploadDownload/image/${username}/${filename}`;
};

// 播放控制
const onVideoPlay = (index) => {
  // 暂停其他正在播放的视频
  if (currentPlayingIndex.value !== -1 && currentPlayingIndex.value !== index) {
    // 这里可以添加暂停其他视频的逻辑
  }
  currentPlayingIndex.value = index;
};

const onVideoPause = (index) => {
  if (currentPlayingIndex.value === index) {
    currentPlayingIndex.value = -1;
  }
};

const onVideoEnded = (index) => {
  currentPlayingIndex.value = -1;
  // 自动播放下一个视频
  playNextVideo(index);
};

const playVideo = (video) => {
  currentVideo.value = video;
  playDialogVisible.value = true;
};

const closePlayDialog = () => {
  playDialogVisible.value = false;
  currentVideo.value = null;
};

const playNextVideo = (currentIndex = -1) => {
  const videos = filteredVideos.value;
  if (videos.length === 0) return;

  let nextIndex;
  if (currentIndex === -1) {
    // 从对话框播放，找到当前视频的索引
    const currentVideoIndex = videos.findIndex(v => v.id === currentVideo.value?.id);
    nextIndex = (currentVideoIndex + 1) % videos.length;
  } else {
    nextIndex = (currentIndex + 1) % videos.length;
  }

  if (playDialogVisible.value) {
    currentVideo.value = videos[nextIndex];
  }
};

const deleteVideo = async (index) => {
  try {
    await ElMessageBox.confirm(
      "确定要删除这个视频吗？此操作不可恢复。",
      "确认删除",
      {
        confirmButtonText: "确定删除",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const videoId = videoUrls.value[index].id;
    const response = await deleteApi({ id: videoId });
    if (response.code === 200) {
      videoUrls.value.splice(index, 1);
      ElMessage.success("删除成功");
    } else {
      ElMessage.error("删除失败");
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error("删除失败:", error);
      ElMessage.error("删除失败，请重试");
    }
  }
};

// 下载视频
const downloadVideo = async (video) => {
  try {
    const downloadUrl = video.videoUrl || video.relativeFilePath;

    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = video.filename;
    link.target = '_blank';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    ElMessage.success('开始下载');
  } catch (error) {
    console.error('下载失败:', error);
    ElMessage.error('下载失败，请重试');
  }
};

// 分享视频
const shareVideo = (video) => {
  ElMessage.info('分享功能开发中...');
};

// 格式化日期
const formatDate = (dateString) => {
  return new Date(dateString).toLocaleDateString('zh-CN');
};

// 格式化文件大小
const formatFileSize = (sizeInMB) => {
  if (sizeInMB < 1) {
    return `${Math.round(sizeInMB * 1024)} KB`;
  } else if (sizeInMB < 1024) {
    return `${sizeInMB.toFixed(1)} MB`;
  } else {
    return `${(sizeInMB / 1024).toFixed(1)} GB`;
  }
};

onMounted(() => {
  getVideos();
});
</script>

<style lang="less" scoped>
.videos-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;

  .header-content {
    display: flex;
    align-items: center;
    gap: 16px;

    .header-icon {
      width: 50px;
      height: 50px;
      background: linear-gradient(135deg, #409eff, #66b1ff);
      border-radius: 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-size: 20px;
    }

    .header-text {
      h2 {
        margin: 0 0 4px 0;
        color: #303133;
        font-size: 20px;
        font-weight: 600;
      }

      p {
        margin: 0;
        color: #606266;
        font-size: 14px;
      }
    }
  }

  .header-actions {
    display: flex;
    gap: 12px;
  }
}

.filter-section {
  margin-bottom: 24px;

  .view-controls {
    display: flex;
    justify-content: flex-end;
  }
}

.videos-content {
  .loading-state {
    text-align: center;
    padding: 60px 20px;

    .el-icon {
      font-size: 32px;
      color: #409eff;
      margin-bottom: 16px;
    }

    p {
      color: #606266;
      font-size: 16px;
    }
  }

  .empty-state {
    text-align: center;
    padding: 60px 20px;
  }

  .grid-view {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
    gap: 24px;

    .video-card {
      background: white;
      border-radius: 16px;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      overflow: hidden;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-4px);
        box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
      }

      .video-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px;
        border-bottom: 1px solid #f5f7fa;

        .video-title {
          margin: 0;
          font-size: 16px;
          font-weight: 500;
          color: #303133;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          flex: 1;
          margin-right: 12px;
        }

        .video-actions {
          .action-btn {
            width: 32px;
            height: 32px;
            padding: 0;
            border-radius: 6px;

            &:hover {
              background: #f5f7fa;
            }
          }
        }
      }

      .video-player-wrapper {
        position: relative;
        background: #000;
        border-radius: 8px;
        overflow: hidden;

        .custom-video-player {
          width: 100%;
          height: 250px;
          object-fit: cover;
          border-radius: 8px;

          &::-webkit-media-controls-panel {
            background: linear-gradient(transparent, rgba(0, 0, 0, 0.8));
          }

          &::-webkit-media-controls-play-button,
          &::-webkit-media-controls-pause-button {
            background-color: rgba(255, 255, 255, 0.9);
            border-radius: 50%;
          }

          &::-webkit-media-controls-timeline {
            background: rgba(255, 255, 255, 0.3);
            border-radius: 2px;
          }

          &::-webkit-media-controls-current-time-display,
          &::-webkit-media-controls-time-remaining-display {
            color: white;
            text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.5);
          }
        }
      }

      .video-info {
        padding: 16px;

        .video-meta {
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 12px;
          color: #909399;

          .video-date {
            font-weight: 500;
          }
        }
      }
    }
  }

  .list-view {
    .video-cell {
      display: flex;
      align-items: center;
      gap: 12px;

      .video-thumbnail {
        width: 60px;
        height: 40px;
        background: linear-gradient(135deg, #409eff, #66b1ff);
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 20px;
      }

      .video-details {
        flex: 1;

        .video-name {
          font-weight: 500;
          color: #303133;
          margin-bottom: 4px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .video-meta-list {
          font-size: 12px;
          color: #909399;

          span {
            margin-right: 12px;
          }
        }
      }
    }
  }
}

.dialog-video-player {
  width: 100%;
  max-height: 70vh;
  background: #000;
  border-radius: 8px;
  overflow: hidden;

  .dialog-video {
    width: 100%;
    height: 60vh;
    object-fit: contain;

    &::-webkit-media-controls-panel {
      background: linear-gradient(transparent, rgba(0, 0, 0, 0.8));
    }

    &::-webkit-media-controls-play-button,
    &::-webkit-media-controls-pause-button {
      background-color: rgba(255, 255, 255, 0.9);
      border-radius: 50%;
      width: 50px;
      height: 50px;
    }

    &::-webkit-media-controls-timeline {
      background: rgba(255, 255, 255, 0.3);
      border-radius: 2px;
      height: 6px;
    }

    &::-webkit-media-controls-current-time-display,
    &::-webkit-media-controls-time-remaining-display {
      color: white;
      text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.5);
      font-size: 14px;
    }

    &::-webkit-media-controls-volume-slider {
      background: rgba(255, 255, 255, 0.3);
      border-radius: 2px;
    }
  }
}

@media (max-width: 768px) {
  .videos-container {
    padding: 15px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;

    .header-actions {
      width: 100%;
      justify-content: center;
    }
  }

  .filter-section {
    .el-col {
      margin-bottom: 12px;
    }

    .view-controls {
      justify-content: center;
    }
  }

  .grid-view {
    grid-template-columns: 1fr;
    gap: 16px;
  }
}
</style>
